orderDetailController = BaseController.extend({
	template:'orderDetail',
	center:'',
	left:'订单详情',
	headerTransparent:false,
	waitOn:function(){
		Meteor.subscribe('orders',{id:parseInt(this.params.id)},{});
		Meteor.subscribe('orderGoods',{order_id:parseInt(this.params.id)},{});
	},
	onRendered:function(self){
	},
	data:function(){
		var self = this;
		return{
			order:Orders.findOne({id:parseInt(self.params.id)}),
			orderGoods:function(){
				var og = OrderGoods.find({order_id:parseInt(self.params.id)}).fetch();
				return og;
			}
		}
	},
})

refundController = BaseController.extend({
	template:'refund',
	center:'',
	left:'我要退款',
	headerTransparent:false,
	waitOn:function(){

	},
	onRendered:function(self){
		$('.gorefund').on('click',function(){
			let reason = $('#reason').val();
			self.post('user/refund',{order_id:self.params.id,refund_reason:reason}).then(function(res){
				self.router.go('order');
			})
		})
	},
	data:function(){
		return{

		}
	},
})


orderController = BaseController.extend({
	template:'order',
	center:'我的订单',
	left:'<a href="#"></a>',
	//bottomShow:true,
	bottomShow: new ReactiveVar(false),
	order_selector:new ReactiveVar({}),
	ordersList:new ReactiveVar([]),
	waitOn:function(){
		this.limit = 30;
		this.state = {};
		this.user_id = 0;
		let self = this;
		Tracker.autorun(function(){
			self.user = self.currentUser();
			self.bottomShow.set(self.showBottom());
			if(self.user){
				self.user_id = self.user.id;
				self.order_selector.set({user_id:self.user_id});
				Meteor.subscribe('orderlist',self.user.id,{id:-1});
				Meteor.subscribe('comments',{user_id:self.user.id});
			}
		});
	},
	onRendered:function(self){
		self.selected(0);
		$('.f7-order-list').on('click','.item-media,.item-title-row,.order-time',function(){
			var id = $(this).data('id');
			self.router.go('order.detail',{id:id});
		})
	},
	onReadyCallBack:function(){
		if(this.scrollData){
			if(this.scrollData.lastIndex >= Orders.find().count()){
					this.scrollData.end = true;
			}else {
				this.scrollData.end = false;
			}
			this.scrollData.lastIndex = Orders.find().count();
			if(!this.scrollData.end){
				this.orderList.set(Orders.find({},{
					sort:this.sort,
					limit:this.limit,
					fields:{
						id:true,
						merchant:true,
						state:true,
						order_no:true,
						pay_time:true,
						is_comment:true,
						total_fee:true,
						pay_fee:true,
						created_at:true,
						user_id:true
					}
				}));
			}
		}
	},
	data:function(){
		var self = this;
		return{
			scroll:'infinite-scroll',
			orderList:function(){
				var data = Orders.find(self.order_selector.get(),{id:-1}).fetch();
				for(var i in data){
					if(data[i]['state'] == 'pay'){
						var c = Comments.find({user_id:self.user_id,order_id:data[i]['id']}).count();
						if(c == 0){
							data[i]['is_comment'] = true;
						}
					}
				}
				return data;
			},
			gopay(state){
				return state == 'nopay';
			}
		}
	},
	events: function (controller) {
		let self = this;
		return {
			'click #all': function (e) {
				self.selected(0);
				self.order_selector.set({user_id:self.user_id});
			},
			'click #nopay': function (e) {
				self.selected(1);
				self.order_selector.set({user_id:self.user_id,state:'nopay'})
			},
			'click #pay': function (e) {
				self.selected(2);
				self.order_selector.set({user_id:self.user_id,state:'pay'})
			},
			'click #refunded': function (e) {
				self.selected(3);
				self.order_selector.set({user_id:self.user_id,'$or':[{state:'refunded'},{state:'apply'}]})
			}
		}
	},
	selected: function (i){
		$(".f7-order-top div").removeClass('f7-order-select').eq(i).addClass('f7-order-select');
	},
})




merBuyController = BaseController.extend({
	template:'merchantBuy',
	center:'买单',
	mainView:'merchantbuy',
	coupon_type:{cash:'现金券',free_cut:'满减券',discount:'折扣券'},
	coupons:new ReactiveVar([]),
	coupon:{},
	coupon_r_id:0,
	distype:'free_time',
	coupon_recode_id:0,
	merbuy:true,
	merchantIt:new ReactiveVar(),
	ntime: new ReactiveVar(),
	waitOn:function(){
		let self = this;
		this.user_id = 0;
		this.get('user/get-time',{}).then(function(res){
			self.ntime.set(res.data);
		}, function (err) {
			console.log(err)
		})
		Tracker.autorun(function(){
			self.user = self.currentUser();
			if(self.user != null){
				self.user_id = self.user.id;
			}
			if(self.user_id > 0){
				self.getCoupon();
			}
			Meteor.subscribe('merchant',{id:parseInt(self.params.query.merchant_id)},{},function(){});
		})
	},
	onRendered:function(self){
		self.merbuy = true;
		var myApp = new Framework7({
			modalButtonOk: "确定"
		});
		var $$ = Dom7;
		//价格变化
		$('#total_money').bind('input propertychange',function(value){
			self.orderMoney();
		});
		$('#no_dis_money').bind('input propertychange',function(value){
			if($('#total_money').val() == '')return;
			self.orderMoney();
		});
		//绑定闲时选择
		$('#discount').change(function(){
			if($(this).is(':checked')){
				self.distype = 'free_time';
				$('#coupon_k').html('选择可用优惠券');
			}
			self.orderMoney();
		});
		$('#open-about').on('click',function(e){
			myApp.popup($('#dispoupop').html());
		});
		$('.pay-go').on('click',function(){
			$(this).attr('disabled',true);
			if(!self.user || self.user_id == 'undefined' || self.user_id == undefined || self.user_id == 0){
				myApp.alert('你未登录，请登录后再购买', ['提示'],function(){
					self.router.go('app.login');
				});
				$(this).attr('disabled',false);
				return;
			}
			let total_fee = $('#total_money').val();
			let no_dis_fee = $('#no_dis_money').val();
			if(total_fee <= 0 || total_fee == ''){
				$(this).attr('disabled',false);
				myApp.alert('支付金额格式不正确', ['提示']);
				return;
			}
			let post_data = {};
			if(self.distype == 'free_time'){
				post_data = {
					merchant_id:parseInt(self.params.query.merchant_id),
					total_fee:total_fee,
					no_dis_fee:no_dis_fee,
					coupon_recode_id:0,
					discount_type:'free_time',
					user_id:self.user_id,
					site_id:$('#site_id').val()
				}
			}else if(self.distype == 'coupon'){
				post_data = {
					merchant_id:parseInt(self.params.query.merchant_id),
					total_fee:total_fee,
					no_dis_fee:no_dis_fee,
					coupon_recode_id:self.coupon_r_id,
					discount_type:'coupon',
					user_id:self.user_id,
					site_id:$('#site_id').val()
				}
			}
			if(self.merbuy){
				self.merbuy = false;
				self.post('user/order',post_data).then(function(res){
					if(res.data.state == 'OK' && res.data.data.message.id){
						var merchantl = self.merchantIt.get();
						var mname = '';
						var list_img = '/img/refunded.png';
						var que = 'order_id='
						+res.data.data.message.id
						+'&order_no='
						+res.data.data.message.order_no+'&mname='+merchantl.name
						+'&pay_fee='+res.data.data.message.pay_fee
						+'&list_image='+merchantl.list_image.path
						self.router.go('payment',{},{query:que});
					}else{
						self.merbuy = true;
						$(this).attr('disabled',false);
						myApp.alert('下单失败，请稍后再试', ['提示']);
					}
				},function(err){
					console.log(err)
				})
			}
		})

		$('body').on('click','.chose-coupon',function(){
			var d = $('.chose-coupon').index(this);
			if(d > -1){
				self.coupon_r_id = $('.chose-coupon').eq(d).data('recid');
				$('#coupon_k').html($('.chose-coupon').eq(d).data('detail'))
				self.distype = 'coupon';
				self.orderMoney();
				$('.close-popup').click();
			}
		})
	},
	data:function(){
		let self= this;
		return{
			merDetail:function(){
				var t = self.ntime.get();
				var m = merchant.findOne({id:parseInt(self.params.query.merchant_id)});
				if(t != 'undefined' && m != 'undefined' && m != undefined && t != undefined){
					m.idle = {};
						for(var i in m.idles){
						if(typeof(m.idles[i].d) != 'undefined' && m.idles[i].d == t.w){
							for(var j in m.idles[i].idle){
								if(m.idles[i].idle[j].start_second < t.t && m.idles[i].idle[j].end_second > t.t){
									m.idle = m.idles[i].idle[j];
								}
							}
						}
					}
				}
				self.merchantIt.set(m);
				return m;
			},
			coupons:function(){
				return self.coupons.get();
			}
		}
	},
	events:function(){
		return {
		}
	},
	getCoupon:function(){
		var self = this;
		this.get('user/user-coupon',{user_id:this.user_id,merchant_id:parseInt(this.params.query.merchant_id)}).then(function(res){
			self.coupons.set(res.data);
		},function(err){
			console.log(err)
		})
	},
	orderMoney:function(){
		var money = 0;
		var smoney = 0;
		var total_money = parseFloat($('#total_money').val());
		var no_dis_money = parseFloat($('#no_dis_money').val()) || 0;
		if(total_money < no_dis_money)return;
		if(total_money && total_money > 0){
			money = total_money;
		}
		smoney = money;
		if(money > 0 && no_dis_money && no_dis_money > 0){
			smoney = money - no_dis_money;
		}
		if(this.distype == 'free_time' && $('#discount').is(':checked')){
			this.get('user/get-idle-money',{money:smoney,user_id:this.user_id,merchant_id:$('#merchant_id').val()}).then(function(res){
				$('#pay_money').val(no_dis_money + parseFloat(res.data.pay_money));
			},function(err){
				console.log(err)
			})
			return;
		}
		if(this.distype == 'coupon'){
			this.get('user/get-coupon-money',{money:smoney,user_id:this.user_id,merchant_id:this.params.query.merchant_id,coupon_recode_id:this.coupon_r_id}).then(function(res){
				$('#discount').attr("checked",false);
				$('#pay_money').val(no_dis_money + parseFloat(res.data.pay_money));
			},function(err){
				console.log(err)
			})
			return;
		}
		if(money < 0){
			money = 0;
		}
		money = Math.round(money*100)/100;
		$('#pay_money').val(money);
		$('.pay-go').data('hr','/payment?m='+money)
	}
})
goodsBuyController = BaseController.extend({
	template:'goodsBuy',
	center:'下单',
	mainView:'goodsbuy',
	monitor_partner_id:0,
	goods_has:true,
	goodsbuy:true,
	goodsIt:new ReactiveVar(),
	waitOn:function(){
		let self = this;
		this.user_id = 0;
		this.class_code = 0;
		Tracker.autorun(function(){
			self.user = self.currentUser();
			if(self.user != null){
				self.user_id = self.user.id;
				self.class_code = self.user.class_code;
			}
			Meteor.subscribe('goods',{id:parseInt(self.params.query.goods_id)},{},function(){});
		})
		this.getPartner();
	},
	onRendered:function(self){
		self.goodsbuy = true;
		var myApp = new Framework7({
			modalButtonOk: "确定"
		});
		var $$ = Dom7;
		$('#class_code').bind('input propertychange',function(value){
			self.class_code = $(this).val();
			self.getPartner();
		});
		$('.pay-go').on('click',function(){
			$(this).attr('disabled',true);
			if(!self.user || self.user_id == 'undefined' || self.user_id == undefined || self.user_id == 0){
				myApp.alert('你未登录，请登录后再购买', ['提示'],function(){
					self.router.go('app.login');
				});
				$(this).attr('disabled',false);
				return;
			}
			if(self.goods_has == false){
				myApp.alert('该商品不存在，无法购买', ['提示'])
				$(this).attr('disabled',false);
				return;
			}
			var total_fee = $('#total_money').val();
			if(total_fee == 0 || total_fee == ''){
				$(this).attr('disabled',false);
				return;
			}
			var postData = {
				goods_str:self.params.query.goods_id,
				monitor_partner_id:self.monitor_partner_id,
				user_id:self.user_id,
				site_id:$('#site_id').val(),
				merchant_id:self.params.query.merchant_id
			}
			if(self.goodsbuy){
				self.goodsbuy = false;
				self.post('user/order',postData).then(function(res){
					if(res.data.state == 'OK' && res.data.data.message.id){
						var goodsl = self.goodsIt.get();
						var mname = '';
						var list_img = '/img/refunded.png';
						var que = 'order_id='
						+res.data.data.message.id
						+'&order_no='
						+res.data.data.message.order_no+'&mname='+goodsl.name
						+'&pay_fee='+res.data.data.message.pay_fee
						+'&list_image='+goodsl.list_img.path
						self.router.go('payment',{},{query:que});
					}else{
						$(this).attr('disabled',false);
						self.goodsbuy = true;
						myApp.alert('下单失败，请稍后再试', ['提示']);
					}
				},function(err){

				})
			}
		})
	},
	data:function(){
		let self= this;
		return{
			goods:function(){
				var g = goods.findOne({id:parseInt(self.params.query.goods_id)});
				self.goodsIt.set(g);
				return g;
			},
			class_code:this.class_code
		}
	},
	getPartner:function(){
		var self = this;
		this.get('user/get-partner',{class_code:this.class_code,goods_id:this.params.query.goods_id}).then(function(res){
			if(res.data.partner_id && res.data.partner_id > 0){
				self.monitor_partner_id = res.data.partner_id;
			}else{
				self.monitor_partner_id = 0;
			}
			self.getGoodsMoney();
		},function(err){
			console.log(err)
		})
	},
	getGoodsMoney:function(){
		var self = this;
		var myApp = new Framework7();
		var postData = {
			goods_str:this.params.query.goods_id,
			monitor_partner_id:this.monitor_partner_id,
			user_id:this.user_id
		}
		this.get('user/get-goods-money',postData).then(function(res){
			if(res.data.status == false){
				self.goods_has = false;
				myApp.alert('该商品不存在，无法购买', ['提示'])
				return;
			}
			$('#pay_money').val(res.data.pay_fee)
		},function(err){
			console.log(err)
		})
	}
})
